//
//  TMGSaleGoldViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/12.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGSaleGoldViewController.h"

@interface TMGSaleGoldViewController ()
@property(nonatomic, strong) UITextField                     *textFiled;
@property(nonatomic, strong) NSArray                        *dataSouce;
@property(nonatomic, strong) STLabel                     *saleLable;
@property(nonatomic, strong) NSString                     *currentGoldPrice;
@end

@implementation TMGSaleGoldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configDataSouce];
    self.title = @"卖出黄金";
    [self configSubView];
    [self configFooterView];
    [self addNotifacations];
    [self sendGoldAssetRequest];
    // Do any additional setup after loading the view.
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(uitextFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)uitextFieldTextDidChangeNotification:(NSNotification*)notify{
    
    if (notify.object == self.textFiled) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            CGFloat ke = [self.textFiled.text floatValue];
            CGFloat money = ke * self.currentGoldPrice.floatValue;
            STTableEasyModel * model = self.dataSouce.lastObject;
            model.detailString = [NSString stringWithFormat:@"%0.2f(元)",money];
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        });

    }
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)configDataSouce{
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0.66*UIScreenWidth, 44)];
    self.textFiled.placeholder = @"输入卖克重量";
    self.textFiled.keyboardType = UIKeyboardTypeDecimalPad;
    
    self.dataSouce = @[
                       [[STTableEasyModel alloc] initWithTextString:@"卖出克重" accessoryView:self.textFiled],
                       [[STTableEasyModel alloc] initWithTextString:@"预计收入" detailString:@"0.00(元)"]];
    [self.tableView reloadData];
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    header.backgroundColor = [UIColor whiteColor];
    
    UIImageView * bannerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 193)];
    bannerImageView.image = [UIImage imageNamed:@"wdebanner"];
    bannerImageView.userInteractionEnabled = YES;
    [header addSubview:bannerImageView];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, 200, 80)
                                                     text:@"266.1\n实时金价(元/克)"
                                                textColor:[UIColor whiteColor]
                                                     font:26
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    titleLable.centerX = UIScreenWidth / 2;
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"实时金价(元/克)" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    [bannerImageView addSubview:titleLable];
    
    [TMUtils fetchCurrentGoldPrice:^(TMCurrentColdModel *currentModel) {
        titleLable.text = [NSString stringWithFormat:@"%@\n实时金价(元/克)",currentModel.latestpri];
        titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"实时金价(元/克)" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        self.currentGoldPrice = currentModel.openpri;
    }];
    
    STLabel * saleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, bannerImageView.bottom, UIScreenWidth, 60)
                                                     text:@"可卖出黄金0.00克"
                                                textColor:TM_firstTextColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    saleLable.backgroundColor = [UIColor whiteColor];
    [header addSubview:saleLable];
    self.saleLable = saleLable;
    saleLable.attributedText = [saleLable.text st_convertAttributeStringWithKeyWord:@"0.00" attributes:@{NSForegroundColorAttributeName:TM_orangeColor}];
    
    header.height = saleLable.bottom;
    //头部橘色
    UIView * headers = [[UIView alloc] initWithFrame:CGRectMake(0, -header.height, UIScreenWidth, 2 * header.height)];
    headers.backgroundColor = TM_orangeColor;
    [header insertSubview:headers atIndex:0];
    
    self.tableView.tableHeaderView = header;
    
}
- (void)configFooterView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60 , 44)
                                                        title:@"确认卖出"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:10
                                              backgroundColor:TM_orangeColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];
    confimButton.st_centerY = 50;
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.detailTextLabel.text = model.detailString;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSelectedConfimButton{
    if (!self.textFiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入重量"];
        return;
    }
    [self presentInputPwdViewController];
}
- (void)presentInputPwdViewController{
    LBPassWordPresentViewController * vc = [LBPassWordPresentViewController new];
    [vc setPwdDidEdited:^(LBPassWordPresentViewController *passVC ,NSString *inputPwd) {
        
        if (inputPwd.length) {
            [self sendSaleGoldAssetRequestWithPwd:inputPwd handle:^(NSString *code) {
                if (!code.length) {
                    [SVProgressHUD showSuccessWithStatus:@"出售成功"];
                    [passVC dismissWithHandle:^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }];
                }else{
                    if ([code containsString:@"密码"]) {
                        passVC.alertLable.hidden = NO;
                        [passVC rightLablebackAnimation];
                    }
                }
            }];
        }
        
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)sendSaleGoldAssetRequestWithPwd:(NSString*)pwd handle:(void(^)(NSString * code))handle{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (pwd.length) {
        [dic setObject:pwd forKey:@"pay_password"];
    }
    if (self.textFiled.text.length) {
        [dic setObject:self.textFiled.text forKey:@"goods_number"];
    }
    [dic setObject:@"2" forKey:@"trade_type"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/order/addOrderSell"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 if (handle) {
                                                     handle(@"");
                                                 }
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 if (handle) {
                                                     handle(error.desc);
                                                 }
                                             }];
}
- (void)sendGoldAssetRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/goldAssets"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array = responseObject[@"data"];
                                                 NSDictionary * firstDic = array[1];
                                                 if ([[firstDic[@"id"] description] isEqualToString:@"2"]) {
                                                     //头部
                                                     NSString * weight = firstDic[@"assets"];
                                                     self.saleLable.text = [NSString stringWithFormat:@"可卖出黄金%@克",weight];
                                                     self.saleLable.attributedText = [_saleLable.text st_convertAttributeStringWithKeyWord:weight attributes:@{NSForegroundColorAttributeName:TM_orangeColor}];
                                                 }
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                             }];
}
@end
